<template>
	<div class="table-box">
		<ProTable
			ref="proTable"
			title="集包管理"
			:columns="columns"
			:requestApi="getTableList"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<!-- 表格 header 按钮 -->
			<template #tableHeader="scope">
				<el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增集包</el-button>
				<el-button type="primary" :icon="Download" @click="downloadUrl">导入集包模版下载</el-button>
				<el-button type="primary" :icon="Printer" plain @click="printAll(scope.selectedList)">批量打印集包</el-button>
				<el-select class="selectClass" v-model="printer" placeholder="选择打印机">
					<el-option v-for="item in printerList" :key="item.name" :label="item.name" :value="item.name" />
				</el-select>
				<!-- <el-button type="primary" :icon="Upload" plain @click="batchAdd" v-auth="'batchAdd'">批量添加用户</el-button> -->
				<!-- <el-button type="primary" :icon="Download" plain @click="downloadFile" v-auth="'export'">导出用户数据</el-button> -->
				<!-- <el-button type="primary" plain @click="toDetail">To 子集详情页面</el-button> -->
				<el-button v-auth="'batchAdd'" type="danger" :icon="Delete" plain :disabled="!scope.isSelected"> 批量删除用户 </el-button>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>
			<!-- 表格操作 -->
			<template #operation="scope">
				<el-button type="primary" link :icon="Document" @click="openInfo(scope.row)">详情</el-button>
				<el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">废弃</el-button>
				<el-button
					v-upload-file="{
						type: ['xls', 'xlsx'],
						size: 5,
						limit: 1
					}"
					@upload="readExcelFile"
					@click="package_no = scope.row.package_no"
					type="primary"
					plain
					:icon="UploadFilled"
					>导入集包</el-button
				>
			</template>
		</ProTable>
		<UserDrawer ref="drawerRef" />
		<el-drawer size="1000" v-model="dialogVisible" title="详情" :with-header="false">
			<infoDrawer v-if="rowID" :rowID="rowID" />
		</el-drawer>
		<ImportExcel ref="dialogRef" />

		<el-dialog v-model="exportDialog" title="导入结果" width="600px" :before-close="handleClose">
			<div>
				<div style="margin-bottom: 20px">
					共<span style="font-size: 16px; color: #000000"> {{ total }}</span> 条,导入成功
					<span style="font-size: 16px; color: green">{{ total - errorList.length }}</span> 条,失败
					<span style="font-size: 16px; color: red">{{ errorList.length }} </span> 条
				</div>
				<el-table v-if="errorList.length" :data="errorList" style="width: 100%" height="500px">
					<el-table-column prop="waybill_no" label="订单号" width="150" />
					<el-table-column prop="error_msg" label="错误原因" />
				</el-table>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button type="primary" @click="exportDialog = false"> 确定 </el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="tsx" name="customers">
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { ref, reactive, onMounted, watch } from "vue";
import { doConnect, doPrintHandover, doPrint } from "@/utils/print";

import { packageList, packageDelete, packageCreate, batchAddOrder, packageLabel } from "@/api/modules/package";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "./components/Drawer.vue";
import infoDrawer from "./components/infoDrawer.vue";
import { CirclePlus, Delete, EditPen, Location, Document, Download, UploadFilled, Printer } from "@element-plus/icons-vue";
import { sheet2Data } from "@/utils/excel";

import XLSX from "xlsx-js-style";
const printerList = ref();
const printer = ref("");

const printLoading = ref();
const back = ref();
watch(back, () => {
	VPrintBack(back);
});
const VPrintBack = //打印返回
	(res: any) => {
		printLoading.value.close();
	};
onMounted(() => {
	let socket = doConnect();
	socket.onmessage = function (event: any) {
		console.log(JSON.parse(event.data));
		let res = JSON.parse(event.data);
		if (res.cmd === "getPrinters") {
			printerList.value = res.printers;
			console.log(printerList.value);
		}
		if (res.cmd === "print") {
			printLoading.value = ElLoading.service({
				lock: true,
				text: "打印中...",
				background: "rgba(0, 0, 0, 0.7)"
			});
		}
		if (res.cmd === "notifyPrintResult" && res.taskStatus === "printed") {
			back.value = res;
		}
		if (res.status == "failed") {
			printLoading.value.close();
			ElMessage.error(res.msg);
		}
	};
});
//批量集包号打印
const printAll = async (list: any) => {
	if (!list.length) {
		ElMessage.error("请选择集包");
		return;
	}
	let arr = list.map((i: any) => {
		return i.package_no;
	});
	packageLabel({
		package_nos: arr
	}).then((res: any) => {
		res.data.list.forEach((item: any) => {
			doPrint([item], res.data.templateURL, printer.value);
		});
	});
};
const dialogVisible = ref(false);
const openInfo = (row: any) => {
	rowID.value = row.package_no;
	dialogVisible.value = true;
};
const rowID = ref(0);
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	// type: 1
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
	return {
		list: data.data,
		total: data.total
		// pageNum: data.pageNum,
		// pageSize: data.pageSize
	};
};
const handleClose = () => {
	exportDialog.value = false;
};
const downloadUrl = () => {
	window.location.href =
		"https://syd-pub.oss-cn-qingdao.aliyuncs.com/download/%E4%B8%80%E8%88%AC%E8%B4%B8%E6%98%93/%E9%9B%86%E5%8C%85%E6%89%AB%E6%8F%8F%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx";
};
const errorList = ref([]);
const total = ref(0);
const package_no = ref("");
const exportDialog = ref(false);
const readExcelFile = async (e: any) => {
	let data = await readFile(e);
	let workbook = XLSX.read(data);
	let worksheet = workbook.Sheets[workbook.SheetNames[0]];
	// data = XLSX.utils.sheet_to_json(worksheet);
	let file = sheet2Data(worksheet, "A");
	// let arrKey = ["weight", "order_no", ""];
	console.log(file[1]);
	let goodList = file.splice(2, file.length - 1);
	let waybill_nos = goodList.map(i => {
		return i[0];
	});
	total.value = waybill_nos.length;
	errorList.value = [];
	batchAddOrder({
		waybill_nos: waybill_nos,
		package_no: package_no.value
	}).then((res: any) => {
		errorList.value = res.data;
		ElMessage.success("上传成功");
		exportDialog.value = true;
		proTable.value.getTableList();
	});
};
/**
 * 把文件按照二进制进行读取
 * @param file
 * @returns
 */
const readFile = (file: File) => {
	return new Promise(resolve => {
		let reader = new FileReader();
		reader.readAsArrayBuffer(file);
		reader.onload = ev => {
			resolve(ev.target?.result);
		};
	});
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
	let newParams = JSON.parse(JSON.stringify(params));
	// newParams.username && (newParams.username = "custom-" + newParams.username);
	return packageList(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const status = reactive([
	{
		userLabel: "启用",
		userStatus: 1
	},
	{
		userLabel: "禁用",
		userStatus: -1
	}
]);
// 表格配置项
const columns: ColumnProps[] = [
	{ type: "selection", fixed: "left", width: 80 },
	// { type: "selection", fixed: "left", width: 80 },
	{ type: "index", label: "#", width: 80, fixed: "left" },
	// { type: "expand", label: "Expand", width: 100 },
	{
		minWidth: 160,
		prop: "package_no",
		label: "集包号",
		search: { el: "input" },
		fixed: "left"
	},
	{
		minWidth: 160,
		prop: "status",
		label: "集包类型",
		render: (scope: { row: any }) => {
			return (
				<>
					<el-tag type={scope.row.size == 1 ? "success" : "danger"}>{scope.row.size == 1 ? "小件" : "大件"}</el-tag>
				</>
			);
		}
	},
	{
		width: 160,
		prop: "count",
		label: "订单数量"
	},
	{
		minWidth: 260,
		prop: "desc",
		label: "描述"
	},
	{
		prop: "created",
		label: "创建时间",
		width: 180
		// search: {
		// 	el: "date-picker",
		// 	span: 1,
		// 	props: {
		// 		type: "datetimerange",
		// 		valueFormat: "YYYY-MM-DD HH:mm:ss",
		// 		defaultTime: [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
		// 	}
		// }
	},
	{ prop: "operation", label: "操作", fixed: "right", width: 300 }
];

// 删除用户信息
const deleteAccount = async (params: any) => {
	await useHandleData(packageDelete, { id: params.id }, `废弃【${params.package_no}】`);
	proTable.value.getTableList();
};

// 导出用户列表
// const downloadFile = async () => {
// 	ElMessageBox.confirm("确认导出用户数据?", "温馨提示", { type: "warning" }).then(() =>
// 		useDownload(exportUserInfo, "用户列表", proTable.value.searchParam)
// 	);
// };

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref();
const openDrawer = (title: string, rowData: any = {}) => {
	let params = {
		title,
		rowData: {
			client_id: rowData.id,
			username: rowData.username,
			status: rowData.status,
			user_mark: rowData.user_mark,
			code: rowData.code,
			area_code: rowData.area_code,
			mobile: rowData.mobile,
			desc: rowData.desc
		},
		isView: title === "查看",
		api: title === "新增" ? packageCreate : title === "编辑" ? packageCreate : "",
		getTableList: proTable.value.getTableList
	};
	drawerRef.value.acceptParams(params);
};
const showDialog = ref(false);
const client_id = ref();
</script>
<style scoped>
.selectClass {
	position: relative;
	top: -8px;
	left: 10px;
}
</style>
